package controller.ProductController;

import bean.OrderForm;
import bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.AppVariable;
import common.ResultAjax;
import services.ProductService;
import services.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
@WebServlet("/get_cart")
public class GetCartServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    //控制层调用服务层
    ProductService productService = new ProductServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json; charset=utf-8");

        //判断登录
        HttpSession session = req.getSession(false);
        if(session==null){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"未登录，请先登录！"));
            resp.getWriter().write(respJson);
            return ;
        }

        User user = (User) session.getAttribute(AppVariable.SESSION_USERINFO_KEY);
        // 获取名为 "cart"+user.getUid() 的Cookie数组
        Cookie[] cookies = req.getCookies();
        OrderForm orderForm = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("cart"+user.getUid())) {
                    String encodedValue = cookie.getValue();
                    String serializedOrderForm = URLDecoder.decode(encodedValue, "UTF-8");
                    // 将序列化的订单对象反序列化为OrderForm对象
                    ObjectMapper objectMapper = new ObjectMapper();
                    orderForm = objectMapper.readValue(serializedOrderForm, OrderForm.class);
                    break;
                }
            }
        }
        String respJson = objectMapper.writeValueAsString(ResultAjax.succeed(orderForm));
        resp.getWriter().write(respJson);
        return ;

    }
}
